﻿
namespace RFIDStation.DeviceDriver.IModules.Impls;

public class ScannerModule : IModule
{
    private readonly ILogger _logger;
    private readonly ViewModel _viewModel;

    public ScannerModule( ILoggerFactory loggerFactory, ViewModel viewModel )
    {
        _logger = loggerFactory.CreateLogger( "扫描器模块" );
        _viewModel = viewModel;
    }

    public async Task StartAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.Scaner.Enable is false ) return;

        try
        {
            _viewModel.Scanner.OnScanSuccessHandler = ( s, e ) =>
            {
                var msg = new Dtos.MsgDto
                {
                    Cmd = "scanner_scan_success",
                    Data = new Dictionary<string, object>
                    {
                        ["val"] = e.Data
                    }
                };

                _viewModel.WebSocketClientNotify( msg );
            };

            _logger.Info( $"注册成功" );

            // 重连机制
            _ = Task.Factory.StartNew( ( ) =>
            {
                while ( true )
                {
                    try
                    {
                        if ( _viewModel.Scanner.IsOpened is false )
                        {
                            _viewModel.Scanner.Open( );
                        }
                    }
                    catch ( Exception ex )
                    {
                        ConsoleWirter.Warning( $"+ [scanner] {_viewModel.Scanner.Config.Connect.ConnectArgs} 连接失败: {ex.Message}" );
                    }

                    Thread.Sleep( 10 * 1000 );
                }
            } );
        }
        catch ( Exception ex )
        {
            _logger.Error( $"注册失败: {ex.Message}" );
        }

        await Task.CompletedTask;
    }

    public async Task StopAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.Scaner.Enable is false ) return;

        try
        {
            _viewModel.Scanner.Close( );

            _logger.Info( $"注销成功" );
        }
        catch ( Exception ex )
        {
            _logger.Error( $"注销失败: {ex.Message}" );
        }

        await Task.CompletedTask;
    }
}
